import os
import logging
import sys
from gui import VideoTranscriptionGUI
from video_processor import VideoProcessor
from text_processor import TextProcessor
from llm_interface import LLMInterface
import subprocess

logger = logging.getLogger(__name__)

class VideoTranscriptionApp:
    def __init__(self):
        logger.info("初始化应用...")
        self.video_processor = VideoProcessor()
        self.text_processor = TextProcessor()
        self.llm_interface = LLMInterface()
        self.gui = VideoTranscriptionGUI(self)
        logger.info("应用初始化完成")

    def process_video(self, video_path, output_path, progress_callback=None, status_callback=None):
        """处理视频文件"""
        try:
            if status_callback:
                status_callback("开始处理视频")
            
            # 提取音频
            if status_callback:
                status_callback("正在提取音频")
            audio_path = self.video_processor.extract_audio(video_path)
            
            # 转写音频
            if status_callback:
                status_callback("正在转写音频为文字")
            text = self.video_processor.transcribe_audio(
                audio_path,
                progress_callback=progress_callback,
                status_callback=status_callback
            )
            
            # 处理转写文本
            if status_callback:
                status_callback("正在处理转写文本")
            processed_text = self.text_processor.process_text(text)
            
            # 保存处理结果
            if status_callback:
                status_callback("正在保存处理结果")
            with open(output_path, 'w', encoding='utf-8') as f:
                f.write(processed_text)
            
            if status_callback:
                status_callback("处理完成")
            
            return output_path
        except Exception as e:
            logger.error(f"处理视频时出错: {str(e)}")
            if status_callback:
                status_callback("处理失败")
            raise

    def open_output_file(self, file_path):
        """打开输出文件"""
        try:
            logger.info(f"正在打开文件: {file_path}")
            if sys.platform == 'win32':
                os.startfile(file_path)
            elif sys.platform == 'darwin':  # macOS
                subprocess.run(['open', file_path])
            else:  # linux
                subprocess.run(['xdg-open', file_path])
            logger.info("文件已打开")
            return True
        except Exception as e:
            logger.error(f"打开文件时出错: {str(e)}", exc_info=True)
            return False

    def change_llm_model(self, model_name):
        self.llm_interface.set_model(model_name)

def main():
    """主函数"""
    try:
        logger.info("启动应用...")
        app = VideoTranscriptionApp()
        app.gui.run()
        logger.info("应用已关闭")
    except Exception as e:
        logger.error(f"应用运行时出错: {str(e)}", exc_info=True)
        raise

if __name__ == "__main__":
    main() 